package com.duofan.gmall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;
    @Value("${sso.redirectUrl}")
    String redirectUrl;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 无需登录即可访问
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value ="token", required = false) String token) {
        if(!StringUtils.isEmpty(token)) {
            //  登录成功携带token
            String username = redisTemplate.opsForValue().get(token);
            session.setAttribute("loginUser", username);
        }
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null) {
            // 未登录,跳转到认证服务器登录
            return "redirect:" + ssoServerUrl + "?redirect_url=" + redirectUrl;
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }
}
